import asyncio
import time

from bleak import BleakClient
from bleak.exc import BleakDeviceNotFoundError

from common import print_service_and_characteristic, disconnected_callback

heartrate_uuid = "00002a37-0000-1000-8000-00805f9b34fb"
electric_quantity_uuid = "00002a19-0000-1000-8000-00805f9b34fb"


async def read_electric_quantity(client: BleakClient):
    """
    读取电量
    """
    while client.is_connected:
        res_data = await client.read_gatt_char(electric_quantity_uuid)
        print(f"{time.strftime('%Y-%m-%d %H:%M:%S')} 读取当前电量 {int(res_data[0])}%")
        await asyncio.sleep(5)


async def notify(client: BleakClient):
    """
    心率通知
    电量通知
    """
    await client.start_notify(heartrate_uuid, notification_handler)
    await client.start_notify(electric_quantity_uuid, notification_handler)

    try:
        while client.is_connected:
            await asyncio.sleep(1)
    except asyncio.CancelledError:
        pass
    finally:
        await client.stop_notify(heartrate_uuid)
        await client.stop_notify(electric_quantity_uuid)


def notification_handler(sender, data):
    """
    心率通知数据
    """
    # print(f"{time.strftime('%Y-%m-%d %H:%M:%S')} 收到通知数据 {sender.uuid} {data.hex()}")
    if sender.uuid == heartrate_uuid:
        print(f"{time.strftime('%Y-%m-%d %H:%M:%S')} 收到心率数据 {int(data[1])}")
    elif sender.uuid == electric_quantity_uuid:
        print(f"{time.strftime('%Y-%m-%d %H:%M:%S')} 收到电量数据 {int(data[0])}")


# 连接到 BLE 设备
async def connect_device(device_address):
    print(f"{time.strftime("%Y-%m-%d %H:%M:%S")} 开始连接 {device_address} ")
    try:
        async with BleakClient(device_address, disconnected_callback) as client:
            print(f"{time.strftime("%Y-%m-%d %H:%M:%S")} 已连接到 {device_address}")
            # 打印
            print_service_and_characteristic(client)

            task1 = asyncio.create_task(read_electric_quantity(client))

            task2 = asyncio.create_task(notify(client))

            await asyncio.gather(task1, task2)
    except BleakDeviceNotFoundError:
        print(f"{time.strftime("%Y-%m-%d %H:%M:%S")} 设备未找到 {device_address}")


async def main():
    await connect_device("A0:9E:1A:DE:45:BB")


# 执行
asyncio.run(main())
